package org.example.admin.common.biz.user;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.example.admin.common.convention.exception.ClientException;
import org.example.admin.common.convention.result.Results;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import static org.example.admin.common.constant.RedisCacheConstant.LOCK_USER_LOGIN;
import static org.example.admin.common.constant.UserConstant.TOKEN;
import static org.example.admin.common.constant.UserConstant.USERNAME;
import static org.example.admin.common.enums.errorEnum.UserErrorCodeEnum.USER_TOKEN_FAIL;

/**
 * 用户消息上下文传递
 *
 * @author weibin
 * @since 2025/10/4 18:29
 */
@RequiredArgsConstructor
public class UserTransmitFilter implements Filter {

    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 忽略不拦截的接口
     */
    private final static List<String> IGNORE_URL = ListUtil.of(
            "/admin/hasUsername",
            "/admin/register",
            "/admin/login",
            "/remote/shortLink/urlTitle"
    );

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;

        String requestURI = httpServletRequest.getRequestURI();
        if (!IGNORE_URL.contains(requestURI)) {
            String username = httpServletRequest.getHeader(USERNAME);
            String token = httpServletRequest.getHeader(TOKEN);

            if (StrUtil.isAllNotBlank(username, token)) {
                Object userInfoJsonStr = stringRedisTemplate.opsForHash().get(LOCK_USER_LOGIN + username, token);
                if (userInfoJsonStr != null) {
                    UserInfoDTO userInfoDTO = JSON.parseObject(userInfoJsonStr.toString(), UserInfoDTO.class);
                    UserContext.setUser(userInfoDTO);
                } else {
                    handleException(servletResponse, JSON.toJSONString(Results.failure(new ClientException(USER_TOKEN_FAIL))));
                    return;
                }
            } else {
                handleException(servletResponse, JSON.toJSONString(Results.failure(new ClientException(USER_TOKEN_FAIL))));
                return;
            }
        }

        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            UserContext.removeUser();
        }
    }

    /**
     * 处里过滤器中抛出的异常
     */
    private void handleException(ServletResponse response, String json) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        response.setCharacterEncoding("UTF-8");
        httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);

        try(PrintWriter writer = httpResponse.getWriter()) {
            writer.write(json);
        } catch (Exception e) {

        }
    }
}